package cn.stylefeng.guns.modular.testCode;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * 签名请求的java版本demo
 * @author demo
 */
public class SignRequestDemo {
    private static final String TOKEN_HEADER = "X-AURORA-TOKEN";

    public static void main(String[] args) throws Exception {
        // post请求demo
       // post("http://10.10.14.24:8925/test1", "", "72d1c5416bbd4ffab1acd96bde8c38c6");
        // get请求demo
        get("http://10.10.14.24:8925/api/oa/getHrmInfo?workcode=23260", "5b39fe78f3124a21af291e0799124eba");
    }

    private static void post(String url, String body, String token) throws Exception {
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setSSLContext(getAllTrustedSslContext())
                .setSSLHostnameVerifier(getAllTrustedVerifier()).build();

        // 创建post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(body, "UTF-8"));
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
        doToken(httpPost, token);

        // 由客户端执行(发送)post请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        System.out.println("\n\n 返回结果："+ EntityUtils.toString(responseEntity) + "\n\n");
        // 释放资源
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
    }

    private static void get(String url, String token)
            throws GeneralSecurityException, IOException {
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setSSLContext(getAllTrustedSslContext())
                .setSSLHostnameVerifier(getAllTrustedVerifier()).build();

        // 创建post请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
        doToken(httpGet, token);

        // 由客户端执行(发送)get请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        System.out.println("\n\n 返回结果：" + EntityUtils.toString(responseEntity) + "\n\n");

        // 释放资源
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
    }

    private static SSLContext getAllTrustedSslContext() throws GeneralSecurityException {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustAllCerts, new SecureRandom());
        return context;
    }

    private static HostnameVerifier getAllTrustedVerifier() {
        return (hostname, session) -> true;
    }

    private static void doToken(HttpRequestBase httpRequestBase, String token) {
        httpRequestBase.setHeader(TOKEN_HEADER, token);
    }
    /**
     *Header字符串转map
     * @param zz
     * @return
     */
    public static Map<String, String> splid(String zz) {
        String[] stepOne = zz.split("\n");
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < stepOne.length; i++) {
            String[] stepTwo = stepOne[i].split(": ");
            if (map.get(stepTwo[0]) == null) {
                map.put(stepTwo[0], stepTwo[1]);
            } else {
                map.put(stepTwo[0], stepTwo[1] + "," + map.get(stepTwo[0]));
            }
        }
        return map;
    }
}